package com.hetwen.demo.server;

import com.litesuits.common.io.IOUtils;
import com.litesuits.common.io.StringCodingUtils;
import com.litesuits.common.utils.ByteUtil;
import com.litesuits.common.utils.HexUtil;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

public class ServerHandler extends IoHandlerAdapter {

    @Override
    public void exceptionCaught(IoSession session, Throwable cause)
            throws Exception {
        super.exceptionCaught(session, cause);
    }

    @Override
    public void messageReceived(IoSession session, Object message)
            throws Exception {
        super.messageReceived(session, message);
        System.out.println("messageReceived:" + message);
        byte[] data = new byte[]{0x01, 0x03, 0x08, (byte) 0xEB, (byte) 0x85, 0x41, 0x05, 0x00, 0x00, 0x41, (byte) 0xC8, (byte) 0xFC, 0x33};
        session.write(HexUtil.encodeHexStr(data));
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        super.messageSent(session, message);
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        super.sessionClosed(session);
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        super.sessionCreated(session);
        InetSocketAddress remoteAddress = (InetSocketAddress) session.getRemoteAddress();
        String host = remoteAddress.getAddress().getHostAddress();
        System.out.println("sessionCreated:" + host);
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status)
            throws Exception {
        super.sessionIdle(session, status);
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        super.sessionOpened(session);
        InetSocketAddress remoteAddress = (InetSocketAddress) session.getRemoteAddress();
        String host = remoteAddress.getAddress().getHostAddress();
        System.out.println("sessionOpened:" + host);
    }

}
